<template>
  <div>
    <van-button
      class="follow-btn"
      round
      size="small"
      v-if="isFollowed"
      @click="onFollow"
      :loading="followLoading"
      >已关注</van-button
    >
    <van-button
      v-else
      class="follow-btn"
      type="info"
      color="#3296fa"
      round
      size="small"
      icon="plus"
      @click="onFollow"
      >关注</van-button
    >
  </div>
</template>

<script>
import { userFollowingsAPI, cancelUserFollowingsAPI } from '@/api'
export default {
  name: 'follow-user',
  data () {
    return {
      followLoading: false
    }
  },
  model: {
    prop: 'isFollowed',
    event: 'update-is_followed'
  },
  props: {
    // value: {
    //   type: Boolean,
    //   required: true
    // },
    isFollowed: {
      type: Boolean,
      required: true
    },
    userId: {
      type: [Number, String, Object],
      required: true
    }
  },
  methods: {
    // 用户关注事件处理函数
    async onFollow () {
      this.followLoading = true
      try {
        if (this.isFollowed) {
          // 取消关注
          await cancelUserFollowingsAPI(this.userId)
          // this.article.is_followed = false
        } else {
          // 添加关注
          await userFollowingsAPI({
            target: this.userId
          })
          // this.article.is_followed = true
        }
        this.$emit('update-is_followed', !this.isFollowed)
      } catch (err) {
        let message = '操作失败，请重试！'
        if (err.response && err.response.status === 400) {
          message = '你不能关注你自己！'
        }
        this.$toast(message)
      }
      this.followLoading = false
    }
  }
}
</script>

<style>
</style>
